package com.lzdongrui.backend.service.impl;

import java.util.List;

import com.lzdongrui.backend.domain.College;
import com.lzdongrui.backend.domain.Major;
import com.lzdongrui.backend.domain.Studentinfo;
import com.lzdongrui.backend.domain.dto.GradeDTO;
import com.lzdongrui.backend.domain.dto.MajorDTO;
import com.lzdongrui.backend.domain.vo.GradeVO;
import com.lzdongrui.backend.mapper.MajorMapper;
import com.lzdongrui.backend.mapper.StudentinfoMapper;
import com.lzdongrui.common.exception.ServiceException;
import com.lzdongrui.common.utils.DateUtils;
import com.lzdongrui.common.utils.StringUtils;
import com.lzdongrui.common.utils.bean.BeanValidators;
import com.lzdongrui.common.utils.snowid.SnowflakeIdWorker;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.lzdongrui.backend.mapper.GradeMapper;
import com.lzdongrui.backend.domain.Grade;
import com.lzdongrui.backend.service.IGradeService;
import org.springframework.transaction.annotation.Transactional;

import javax.validation.Validator;

/**
 * 班级Service业务层处理
 * 
 * @author wyh
 * @date 2023-05-05
 */
@Service
public class GradeServiceImpl implements IGradeService 
{
    private static final Logger log = LoggerFactory.getLogger(MajorServiceImpl.class);

    @Autowired
    private GradeMapper gradeMapper;

    @Autowired
    private SnowflakeIdWorker snowflakeIdWorker;

    @Autowired
    protected Validator validator;

    @Autowired
    private MajorMapper majorMapper;

    @Autowired
    private StudentinfoMapper studentinfoMapper;

    /**
     * 查询班级
     * 
     * @param id 班级主键
     * @return 班级
     */
    @Override
    public Grade selectGradeById(Long id)
    {
        return gradeMapper.selectGradeById(id);
    }

    /**
     * 查询班级列表
     * 
     * @param gradeDTO 班级
     * @return 班级
     */
    @Override
    public List<GradeVO> selectGradeList(GradeDTO gradeDTO)
    {
        return gradeMapper.selectGradeList(gradeDTO);
    }

    @Override
    public List<Grade> selectGradeAllList(Grade grade) {
        return gradeMapper.selectGradeAllList(grade);
    }

    @Override
    public String importGrade(List<GradeDTO> gradeDTOS, boolean updateSupport, Long operator) {
        if (StringUtils.isNull(gradeDTOS) || gradeDTOS.size() == 0) {
            throw new ServiceException("导入班级数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (GradeDTO gradeDTO : gradeDTOS) {
            try {
                //查询专业数据是否存在
                Major majorInfo = majorMapper.selectMajorInfoByCode(gradeDTO.getMajorCode());
                if(!StringUtils.isNull(majorInfo)){
                    //查询班级的数据是否有重复（包含code、名称）
                    Grade grade = new Grade();
                    BeanUtils.copyProperties(gradeDTO, grade);
                    Grade n = gradeMapper.selectGradeInfo(grade);
                    if (StringUtils.isNull(n)) {
                        Grade grade1 = new Grade();
                        BeanUtils.copyProperties(gradeDTO, grade1);
                        grade1.setId(snowflakeIdWorker.nextId());
                        grade1.setMajorId(majorInfo.getId());
                        grade1.setOperator(operator);
                        BeanValidators.validateWithException(validator, grade1);
                        this.insertGrade(grade1);
                        successNum++;
                        successMsg.append("<br/>" + successNum + "、班级Code " + gradeDTO.getMajorCode() + "、班级 " + gradeDTO.getName() + " 导入成功");
                    } else if (updateSupport) {
                        Grade grade2 = new Grade();
                        BeanUtils.copyProperties(gradeDTO, grade2);
                        grade2.setId(n.getId());
                        grade2.setMajorId(majorInfo.getId());
                        grade2.setOperator(operator);
                        BeanValidators.validateWithException(validator, grade2);
                        this.updateGrade(grade2);
                        successNum++;
                        successMsg.append("<br/>" + successNum + "、班级Code " + gradeDTO.getMajorCode() + "、班级 " + gradeDTO.getName() + " 更新成功");
                    } else {
                        failureNum++;
                        failureMsg.append("<br/>" + failureNum + "、班级 " + gradeDTO.getName() + " 已存在");
                    }
                }else{
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、专业Code " + gradeDTO.getMajorCode() + " 不存在");
                }
                //返回异常数据
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、班级 " + gradeDTO.getName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    /**
     *毕业班级
     *
     * @param grade
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int finishSchool(Grade grade) {
        int ret = 0;
        List<Grade>  gradeList  =  gradeMapper.selectAllInfoBySchoolYear(grade.getSchoolYear());
        if(gradeList.size() != 0){
//            for (Grade grade1:gradeList){
//                //获取该班级的学生信息
//                List<Studentinfo> studentinfoList = studentinfoMapper.selectStudentinfoByGradeId(grade1.getId());
//                for (Studentinfo studentinfo:studentinfoList){
//                    Studentinfo UpdateStu = new Studentinfo();
//                    UpdateStu.setId(studentinfo.getId());
//                    UpdateStu.setIsAtSchool(2);
//                    studentinfoMapper.updateStudentinfo(UpdateStu);
//                }
//                Grade updateGrpInfo =  new Grade();
//                updateGrpInfo.setId(grade1.getId());
//                updateGrpInfo.setIsFinishSchool(2);
//                updateGrpInfo.setOperator(grade1.getOperator());
//                ret = gradeMapper.updateGrade(updateGrpInfo);
//            }
            //将整个学年的班级关闭
            ret = gradeMapper.updateGradeBySchoolYear(grade.getSchoolYear());
            //将整个所属学年的学生关闭
            ret = studentinfoMapper.updateStudentinfoBySchoolYear(grade.getSchoolYear());
        }else{
            throw new ServiceException("请检查该学年是否存在班级");
        }
        return ret;
    }

    /**
     * 新增班级
     * 
     * @param grade 班级
     * @return 结果
     */
    @Override
    public int insertGrade(Grade grade)
    {
        int ret = 0;
        Grade n = gradeMapper.selectGradeInfo(grade);
        if (StringUtils.isNull(n)) {
            grade.setId(snowflakeIdWorker.nextId());
            grade.setCreateTime(DateUtils.getNowDate());
            grade.setIsFinishSchool(1);
            ret = gradeMapper.insertGrade(grade);
        }else{
            throw new ServiceException("请检查班级代码和名称是否有重复");
        }
        return ret;
    }

    /**
     * 修改班级
     * 
     * @param grade 班级
     * @return 结果
     */
    @Override
    public int updateGrade(Grade grade)
    {
        int ret = 0;
        Grade n = gradeMapper.selectGradeInfo(grade);
        if (n.getId().equals(grade.getId())) {
            grade.setUpdateTime(DateUtils.getNowDate());
            ret = gradeMapper.updateGrade(grade);
        }else{
            throw new ServiceException("请检查班级代码和名称是否有重复");
        }
        return ret;
    }

    /**
     * 批量删除班级
     * 
     * @param ids 需要删除的班级主键
     * @return 结果
     */
    @Override
    public int deleteGradeByIds(Long[] ids)
    {
        return gradeMapper.deleteGradeByIds(ids);
    }

    /**
     * 删除班级信息
     * 
     * @param id 班级主键
     * @return 结果
     */
    @Override
    public int deleteGradeById(Long id)
    {
        return gradeMapper.deleteGradeById(id);
    }

}
